<?php
class Helper_BSS_Normal
{
	/**
	 * 查找替换字符串中间字符 
	 */
	static function strMiddleReduce($string, $max=54, $rep='...') 
	{
		$strlen = strlen($string);
		if ($strlen <= $max)
		{
			return $string;
		}
		$lengthtokeep = $max - strlen($rep);
		$start = 0;
		$end = 0;
		if ($lengthtokeep%2 == 0)
		{
			$start = $lengthtokeep/2;
			$end = $start;
		}
		else
		{
			$start = intval($lengthtokeep/2);
			$end = $start + 1;
		}
		$i = $start;
		$tmp_string = $string;
		while ($i < $strlen)
		{
			if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ')
			{
				$tmp_string = substr($tmp_string, 0, $i) . $rep;
				$return = $tmp_string;
			}
			$i++;
		}
		$i = $end;
		$tmp_string = strrev($string);
		while ($i < $strlen)
		{
			if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ')
			{
				$tmp_string = substr($tmp_string, 0, $i);
				$return .= strrev($tmp_string);
			}
			$i++;
		}
		return mb_substr($string, 0, $start, 'utf8') . $rep . mb_substr($string, - $end, NULL, 'utf8');
		return $return;
	}
	
	static function buildCondition()
	{
		$ret = $_GET;
		unset($ret['namespace']);
		unset($ret['controller']);
		unset($ret['action']);
		unset($ret['ps']);
		unset($ret['cp']);
		return Helper_BSS_Normal::mysqlEscape($ret);
	}
	
	static function mysqlEscape($arr)
	{
		foreach ($arr as &$a)
		{
			if (is_array($a))
			{
				$a = Helper_BSS_Normal::mysqlEscape($a);
			}
			else
			{
				$a = mysql_escape_string(trim($a));
			}
		}
		unset($a);
		return $arr;
	}
	
	static function genToken($extra = false)
	{
		if (isset($GLOBALS[Q::ini('unique_token_name')]) && ! $extra)
		{
			return $GLOBALS[Q::ini('unique_token_name')];
		}
		session_start();
		$expire_time = CURRENT_TIMESTAMP + Q::ini('unique_token_life_time');
		$key = Helper_BSS_Normal::genString('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 15);
		if (isset($_SESSION[Q::ini('unique_token_name')]))
		{
			while (array_key_exists($key, $_SESSION[Q::ini('unique_token_name')]))
			{
				$key = Helper_BSS_Normal::genString('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 15);
			}
		}
		$_SESSION[Q::ini('unique_token_name')][$key] = $expire_time;
		if ( ! $extra)
		{
			$GLOBALS[Q::ini('unique_token_name')] = $key;
		}
		foreach ($_SESSION[Q::ini('unique_token_name')] as $k => $et)
		{
			if ($et < CURRENT_TIMESTAMP)
			{
				unset($_SESSION[Q::ini('unique_token_name')][$k]);
			}
		}
		session_write_close();
		return $key;
	}
	
	static function genString($input_str, $len)
	{
		$count = strlen($input_str);
		$output_str = '';
		for ($i = 0; $i < $len; $i++)
		{
			$output_str .= $input_str[mt_rand(0, $count - 1)];
		}
		return $output_str;
	}
	
	static function getProductImgUrl(&$product, $key = 'number')
	{
		foreach ($product as &$p)
		{
			if ($p[$key])
			{
				$p['pic_url'] = Helper_BSS_API::getProductImageUrl($p[$key]);
			}
			else
			{
				$p['pic_url'] = array();
			}
		}
		unset($p);
	}
	
	static function getIniOne($flag, $search_key, $search_value, $result_key, $ini='custom_flag')
	{
		foreach (Q::ini($ini.'/'.$flag) as  $key => $value)
		{
			if ($value[$search_key] == $search_value)
			{
				return $value[$result_key];
			}
		}
		return '';
	}
	
	static function getIniAll($flag, $search, $ini='custom_flag')
	{
		$match = array();
		foreach (Q::ini($ini . '/' . $flag) as $key => $value)
		{
			$match_flag = true;
			foreach ($search as $search_key => $search_value)
			{
				if ($value[$search_key] != $search_value)
				{
					$match_flag = false;
				}
			}
			if ($match_flag)
			{
				$match[] = $value;
			}
		}
		return $match;
	}
	
	static function getPeriod($begin_date, $end_date, $period)
	{
		$begin_time_stamp = strtotime($begin_date);
		$end_time_stamp = strtotime($end_date);
		$period_arr = array();
		if ($period == 'daily')
		{
			while ($begin_time_stamp <= $end_time_stamp)
			{
				$arr['begin'] = date('Y-m-d H:i:s', $begin_time_stamp);
				$current_end_stamp = strtotime(date('Y-m-d 23:59:59', $begin_time_stamp));
				if ($current_end_stamp > $end_time_stamp)
				{
					$arr['end'] = date('Y-m-d H:i:s', $end_time_stamp);
				}
				else
				{
					$arr['end'] = date('Y-m-d H:i:s', $current_end_stamp);
				}
				$period_arr[] = $arr;
				$begin_time_stamp = $current_end_stamp + 1;
			}
		}
		if ($period == 'weekly')
		{
			while ($begin_time_stamp <= $end_time_stamp)
			{
				$arr['begin'] = date('Y-m-d H:i:s', $begin_time_stamp);
				$current_end_stamp = strtotime(date('Y-m-d 23:59:59', strtotime(date('Y-m-d H:i:s', $begin_time_stamp) . '+ ' . (7 - date('N', $begin_time_stamp)) . ' day')));
				if ($current_end_stamp > $end_time_stamp)
				{
					$arr['end'] = date('Y-m-d H:i:s', $end_time_stamp);
				}
				else
				{
					$arr['end'] = date('Y-m-d H:i:s', $current_end_stamp);
				}
				$period_arr[] = $arr;
				$begin_time_stamp = $current_end_stamp + 1;
			}
		}
		if ($period == 'monthly')
		{
			while ($begin_time_stamp <= $end_time_stamp)
			{
				$arr['begin'] = date('Y-m-d H:i:s', $begin_time_stamp);
				$current_end_stamp = strtotime(date('Y-m-t 23:59:59', $begin_time_stamp));
				if ($current_end_stamp > $end_time_stamp)
				{
					$arr['end'] = date('Y-m-d H:i:s', $end_time_stamp);
				}
				else
				{
					$arr['end'] = date('Y-m-d H:i:s', $current_end_stamp);
				}
				$period_arr[] = $arr;
				$begin_time_stamp = $current_end_stamp + 1;
			}
		}
		return $period_arr;
	}
	
	static function discount(&$data)
	{
		foreach ($data as &$d)
		{
			$total = $d['s_fee'];
			foreach ($d['item'] as $di)
			{
				$total += $di['quantity'] * $di['price'];
				if (isset($di['attr']) && $di['attr'])
				{
					foreach ($di['attr'] as $dia)
					{
						if ($dia['price'])
						{
							if ($dia['prefix'] == '+')
							{
								$total += $di['quantity'] * $dia['price'];
							}
							if ($dia['prefix'] == '-')
							{
								$total -= $di['quantity'] * $dia['price'];
							}
						}
					}
				}
			}
			$d['discount'] = $total - $d['amount'];
		}
		unset($d);
	}
	
	static function time_difference($time)
	{
		$timezone = date_default_timezone_get();
		date_default_timezone_set("UTC");
		$ret = '';
		$years = (date('Y', $time) - 1970);
		if ($years)
		{
			$ret .= $years . '年';
		}
		$months =(date('n',$time) - 1);
		if ($months)
		{
			$ret .= $months . '月';
		}
		$days = (date('j', $time) - 1);
		if ($days)
		{
			$ret .= $days . '天';
		}
		$hours = (date('G', $time));
		if ($hours)
		{
			$ret .= $hours . '时';
		}
		$mins = (date('i', $time));
		if ($mins)
		{
			$ret .= $mins . '分';
		}
		$secs = (date('s', $time));
		if ($secs)
		{
			$ret .= $secs . '秒';
		}
		date_default_timezone_set($timezone);
		return $ret;
	}
	
	static function assembledAmazonOrdersToArray($orders, $shop_id)
	{
		$sales_order = array();
		foreach ($orders as $k => $order)
		{
			if ($order->isSetAmazonOrderId())
			{
				$sales_order[$k]['shop_order_number'] = $order->getAmazonOrderId();
				$sales_order[$k]['transaction_id'] = $order->getAmazonOrderId();
			}
			if ($order->isSetFulfillmentChannel())
			{
				$sales_order[$k]['param']['channel'] = $order->getFulfillmentChannel();
			}
			if ($order->isSetShippingAddress())
			{
				$shippingAddress = $order->getShippingAddress();
				$sales_order[$k]['fullname'] = $shippingAddress->getName();
				$sales_order[$k]['street1'] = $sales_order[$k]['street2'] = '';
				if ($shippingAddress->isSetAddressLine1())
				{
					$sales_order[$k]['street1'] = $shippingAddress->getAddressLine1();
				}
				if ($shippingAddress->isSetAddressLine2())
				{
					$sales_order[$k]['street2'] = $shippingAddress->getAddressLine2();
				}
				if ($shippingAddress->isSetAddressLine3())
				{
					$sales_order[$k]['street2'] = $sales_order[$k]['street2'] . ' ' . $shippingAddress->getAddressLine3();
				}
				if ($shippingAddress->isSetStateOrRegion())
				{
					$sales_order[$k]['state'] = $shippingAddress->getStateOrRegion();
				}
				if ($shippingAddress->isSetCity())
				{
					$sales_order[$k]['city'] = $shippingAddress->getCity();
				}
				if (! isset($sales_order[$k]['city']))
				{
					$sales_order[$k]['city'] = $shippingAddress->getStateOrRegion();
				}
				if (! isset($sales_order[$k]['state']))
				{
					$sales_order[$k]['state'] = $shippingAddress->getCity();
				}
				if ($shippingAddress->isSetCountryCode())
				{
					$country = Country::find('code=?', $shippingAddress->getCountryCode())->asArray()->getOne();
					$sales_order[$k]['country'] = $country ? $country['en_name'] : $shippingAddress->getCountryCode();
					$sales_order[$k]['country_cn'] = $country ? $country['cn_name'] : '';
				}
				$sales_order[$k]['zip'] = $shippingAddress->getPostalCode();
				if ($shippingAddress->isSetPhone())
				{
					$sales_order[$k]['phone'] = $shippingAddress->getPhone();
				}
			}
			if ($order->isSetBuyerEmail())
			{
				$sales_order[$k]['email'] = $order->getBuyerEmail();
			}
			if ($order->isSetBuyerName())
			{
				$sales_order[$k]['shop_buyer_id'] = $order->getBuyerName();
			}
			if ($order->isSetOrderTotal())
			{
				$orderTotal = $order->getOrderTotal();
				if ($orderTotal->isSetCurrencyCode())
				{
					$currency = Currency::find('code=?', $orderTotal->getCurrencyCode())->asArray()->getOne();
					$sales_order[$k]['currency_id'] = $currency['id'];
					$sales_order[$k]['currency_rate'] = $currency['rate'];
				}
				if ($orderTotal->isSetAmount())
				{
					$sales_order[$k]['amount'] = $orderTotal->getAmount();
				}
			}
			if ($order->isSetPurchaseDate())
			{
				$sales_order[$k]['sales_time'] = date('Y-m-d H:i:s', strtotime($order->getPurchaseDate()));
			}
			$sales_order[$k]['shop_id'] = $shop_id;
			$sales_order[$k]['shipping_fee'] = 0;
			$sales_order[$k]['discount'] = 0;
			$sales_order[$k]['shipping_method'] = Shipping_Method::getShippingMethodByCode('GZ_R_SG_Package');
			$sales_order[$k]['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/amazon/value');
			$sales_order[$k]['paid_time'] = NULL;
		}
		return $sales_order;
	}
	
	static function assembledAmazonItemsToArray($orderItemList)
	{
		$items = array();
		$shipping_fee = $discount = 0;
		foreach ($orderItemList as $key => $orderItem)
		{
			$new_item = array();
			$OrderItemQuantity = ($orderItem->getQuantityOrdered()) ? $orderItem->getQuantityOrdered() : 0;
			if ($orderItem->isSetSellerSKU())
			{
				$new_item['product_basic_number'] = substr($orderItem->getSellerSKU(), 0, 7);
				$new_item['quantity'] = $OrderItemQuantity;
				if ($orderItem->isSetOrderItemId())
				{
					$new_item['shop_item_id'] = $orderItem->getOrderItemId();
				}
				if ($orderItem->isSetItemPrice())
				{
					$itemPrice = $orderItem->getItemPrice();
					if ($itemPrice->isSetAmount())
					{
						$new_item['sales_price'] = $itemPrice->getAmount();
					}
				}
				if ($orderItem->isSetShippingPrice())
				{
					$shippingPrice = $orderItem->getShippingPrice();
					if ($shippingPrice->isSetAmount())
					{
						$shipping_fee += $shippingPrice->getAmount();
					}
				}
				if ($orderItem->isSetShippingDiscount())
				{
					$shippingDiscount = $orderItem->getShippingDiscount();
					if ($shippingDiscount->isSetAmount())
					{
						$shipping_fee -= $shippingDiscount->getAmount();
					}
				}
				if ($orderItem->isSetPromotionDiscount())
				{
					$promotionDiscount = $orderItem->getPromotionDiscount();
					if ($promotionDiscount->isSetAmount())
					{
						$discount += $promotionDiscount->getAmount();
					}
				}
				if (empty($new_item['quantity']))
				{
					unset($new_item);
					continue;
				}
				$new_item['sales_price'] = $new_item['sales_price']/$new_item['quantity'];
				$items[] = $new_item;
			}
		}
		return array('item' => $items, 'shipping_fee' => $shipping_fee, 'discount' => $discount);
	}
	
	static function dimensionResend($condition, $resend_where, $where)
	{
		$current = array_shift($condition);
		$resend_count = QDB::getConn()->execute('select ' . $current . ',count(' . $current . ') as count from sales_order left join sales_order_customer_info on sales_order_customer_info.sales_order_id=sales_order.id where ' . $resend_where . ' group by ' . $current)->fetchAll();
		$all_count = QDB::getConn()->execute('select ' . $current . ',count(' . $current . ') as count from sales_order left join sales_order_customer_info on sales_order_customer_info.sales_order_id=sales_order.id where ' . $where . ' group by ' . $current)->fetchAll();
		$resend = array();
		if (empty($condition))
		{
			foreach ($resend_count as $r)
			{
				$resend[$current][$r[$current]]['count'] = $r['count'];
			}
			foreach ($all_count as $a)
			{
				if ($a[$current])
				{
					$count = isset($resend[$current][$a[$current]]['count']) ? $resend[$current][$a[$current]]['count'] : 0;
					$resend[$current][$a[$current]]['count'] = $count;
					$resend[$current][$a[$current]]['all_count'] = $a['count'];
				}
			}
			return $resend;
		}
		foreach ($resend_count as $r)
		{
			$resend[$current][$r[$current]]['count'] = $r['count'];
			foreach ($all_count as $a)
			{
				if ($a[$current])
				{
					if ($a[$current] == $r[$current])
					{
						$resend[$current][$r[$current]]['all_count'] = $a['count'];
					}
				}
			}
			$resend[$current][$r[$current]]['detail'] = Helper_BSS_Normal::dimensionResend($condition, $resend_where . ' and ' . $current . '=\'' . $r[$current] . '\'', $where . ' and ' . $current . '=\'' . $r[$current] . '\'');
		}
		return $resend;
	}
	
	static function getResendHtml($result)
	{
		if (isset($result['shipping_method']))
		{
			foreach ($result['shipping_method'] as $k => $rs)
			{
				$shipping_method = Shipping_Method::find('id=?', $k)->asArray()->getOne();
				echo '<li style="margin: 5px 10px; color: red;" class="parent">' . $shipping_method['name'] . '：（'.$rs['count'].'/'.$rs['all_count'].'）<ul style="list-style: circle;">';
				if (isset($rs['detail']))
				{
					 Helper_BSS_Normal::getResendHtml($rs['detail']);
				}
				echo '</ul>';
			}
		}
		elseif (isset($result['resend_reason']))
		{
			foreach ($result['resend_reason'] as $rrk => $rr)
			{
				echo '<li style="margin: 5px 10px; color: black;" class="parent">'.Helper_BSS_Normal::getIniOne('sales_order_resend_reason', 'value', $rrk, 'name').'：（'.$rr['count'].'/'.$rr['all_count'].'）<ul style="list-style: circle;">';
				if (isset($rr['detail']))
				{
					Helper_BSS_Normal::getResendHtml($rr['detail']);
				}
				echo '</ul>';
			}
		}
		elseif (isset($result['country']))
		{
			foreach ($result['country'] as $rck => $rc)
			{
				echo '<li style="margin: 5px 10px; color: green;" class="parent">'.$rck.'：（'.$rc['count'].'/'.$rc['all_count'].'）<ul style="list-style: circle;">';
				if (isset($rc['detail']))
				{
					Helper_BSS_Normal::getResendHtml($rc['detail']);
				}
				echo '</ul>';
			}
		}
	}
	
	/**
	 * 获取数据表字段数据
	 * @param 表名 $table_name
	 * @param 字段名 $column_name
	 */
	static function getTableColunmData($table_name, $column_name = 'path')
	{
		$data = QDB::getConn()->execute('select * from ' . $table_name)->fetchCol($column_name);
		return $data;
	}
	
	/**
	 * 生成随机字符串
	 * @param 字符串长度 $length
	 * @param 对比数组 $exists_array
	 * @param 生成规则 $rule
	 */
	static function generate($length, $exists_array = array(), $rule = 'md5')
	{
		if ($rule == 'md5')
		{
			$str = substr(str_shuffle(md5(CURRENT_USER_NAME . CURRENT_TIMESTAMP)), 0, $length);
			while (in_array($str, $exists_array))
			{
				$str = substr(str_shuffle(md5(CURRENT_USER_NAME . CURRENT_TIMESTAMP)), 0, $length);
			}
			return $str;
		}
	}
	
	static function createFolder($path, $mode = 0777)
	{
		return is_dir($path) or (Helper_BSS_Normal::createFolder(dirname($path)) and mkdir($path, $mode));
	}
	
	static function getDirlist($base_dir)
	{
		$fso = @opendir($base_dir);
		$files = array();
		while($flist = @readdir($fso))
		{
			if ($flist != '.' && $flist != '..' && $flist != '.svn')
			{
				$files[] = $flist;
				$filectime[] = filectime($base_dir . '/' . $flist);
			}
		}
		@closedir($fso);
		@ array_multisort($filectime, SORT_DESC, SORT_NUMERIC, $files);
		return $files;
	}
	
	static function upload($file, $path)
	{
		if ( ! empty($file))
		{
			if ($file['error'] > 0)
			{
				switch ($file['error'])
				{
					  case 1:  return array('ack' => FAILURE, 'message' => 'File exceeded upload_max_filesize'); break;
				      case 2:  return array('ack' => FAILURE, 'message' => '不能超过800M'); break; 
				      case 3:  return array('ack' => FAILURE, 'message' => 'File only partially uploaded'); break;
				      case 4:  return array('ack' => FAILURE, 'message' => 'No file uploaded'); break;
				}
			}
			else
			{
				$fileTypes = array('gif', 'png', 'jpg', 'jpeg', 'txt');
				$fileParts = pathinfo($file['name']);
				if ( ! in_array($fileParts['extension'] , $fileTypes))
				{
				 	 return array('ack' => FAILURE, 'message' => '文件类型错误，请重新选择文件!<br>只允许gif,png,jpg,jpeg,txt类型的文件');
				}
				if(file_exists($path . '/' . $file['name']))
				{
					unlink($path . '/' . $file['name']);
				}
				$result = move_uploaded_file($file["tmp_name"], $path . '/' . $file['name']);
				if ($result)
				{
					return array('ack' => SUCCESS, 'message' => '文件已成功上传！');
				}
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '文件名称不存在!');
		}
	}
	
	//删除目录及目录下的所有文件
	static function remove_directory($dir)
	{
		if ($handle = opendir("$dir"))
		{
			while (false !== ($item = readdir($handle)))
			{
				if ($item != "." && $item != "..")
				{
					if (is_dir("$dir/$item"))
					{
						Helper_BSS_Normal::remove_directory("$dir/$item");
					}
					else
					{
						unlink("$dir/$item");
					}
				}
			}
			closedir($handle);
			rmdir($dir);
		}
	}
	
	static function xcopy($source, $destination)
	{
		if (! is_dir($source))
		{
			return false;
		}
		if (! is_dir($destination))
		{
			Helper_BSS_Normal::createFolder($destination);
		}
		$handle = opendir($source);
		@mkdir($destination);
		while (($entry= readdir($handle)) !== false)
		{
			if (($entry != '.') && ($entry != '..'))
			{
				if (is_dir($source . '/' . $entry))
				{
					Helper_BSS_Normal::xcopy($source. '/' . $entry, $destination . '/' . $entry);
				}
				else
				{
					copy($source . '/' . $entry, $destination . '/' . $entry);
				}
			}
		}
		return true;
	}
	
	static function AliExpressDateTransfer($aliexpress_date)
	{
		return date('Y-m-d H:i:s', strtotime(substr($aliexpress_date, 0, 14) . substr($aliexpress_date, -5)));
	}
	
	static function isMobile()
	{
		if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
		{
			return true;
		}
		if (isset($_SERVER['HTTP_VIA']))
		{
			return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
		}
		if (isset($_SERVER['HTTP_USER_AGENT']))
		{
			$clientkeywords = array(
				'nokia',
				'sony',
				'ericsson',
				'mot',
				'samsung',
				'htc',
				'sgh',
				'lg',
				'sharp',
				'sie-',
				'philips',
				'panasonic',
				'alcatel',
				'lenovo',
				'iphone',
				'ipod',
				'blackberry',
				'meizu',
				'android',
				'netfront',
				'symbian',
				'ucweb',
				'windowsce',
				'palm',
				'operamini',
				'operamobi',
				'openwave',
				'nexusone',
				'cldc',
				'midp',
				'wap',
				'mobile'
			);
			if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
			{
				return true;
			}
		}
		if (isset($_SERVER['HTTP_ACCEPT']))
		{
			if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false) || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))
			{
				return true;
			}
		}
	}
	
	static function sendMail($subject, $body, $group)
	{
		require_once (Q::ini('custom_system/lib_dir') . 'PHPMailer/class.phpmailer.php');
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->CharSet = Q::ini('custom_system/mail_config_set/charset');
		$mail->Host = Q::ini('custom_system/mail_config_set/host');
		$mail->SMTPAuth = Q::ini('custom_system/mail_config_set/smtp_auth');
		$mail->Username = Q::ini('custom_system/mail_config_set/username');
		$mail->Password = Q::ini('custom_system/mail_config_set/password');
		$mail->Port = Q::ini('custom_system/mail_config_set/port');
		$mail->SMTPSecure = 'ssl';
		$mail->SetFrom(Q::ini('custom_system/mail_config_set/from'), Q::ini('custom_system/system_secondary_name'));
		foreach (Q::ini('custom_system/mail_group/' . $group) as $g)
		{
			$mail->AddAddress($g['value'], $g['name']);
		}
		$mail->Subject = $subject;
		$mail->Body = $body;
		$mail->Send();
		return true;
	}
	
	static function toTimeZone($from, $from_tz, $to_tz = '', $format = 'Y-m-d H:i:s')
	{
		if ( ! $to_tz)
		{
			$to_tz = Q::ini('l10n_default_timezone');
		}
		$datetime = new DateTime($from, new DateTimeZone($from_tz));
		$datetime->setTimezone(new DateTimeZone($to_tz));
		return $datetime->format($format);
	}
	
	static function timeStringToStandard($time)
	{
		return date('Y-m-d H:i:s', strtotime($time));
	}
	
	/**
	 * 根据内容获取TCPDF地址单字体
	 * @param 地址 、 国家英文名、国家中文名、国家二字码    $content
	 * @return string	$font	选择字体
	 */
	static function getPdfAddFont($content)
	{
		$country2font = array(
				'日本' => 'cid0jp',
				'韩国' => 'cid0kr',
				'泰国' => 'freeserifi',
				'中国' => 'cid0cs',
				'Japan' => 'cid0jp',
				'Korea, Republic of' => 'cid0kr',
				'Korea, South' => 'cid0kr',
				'Thailand' => 'freeserifi',
				'China' => 'cid0cs',
				'JP' => 'cid0jp',
				'KR' => 'cid0kr',
				'TH' => 'freeserifi',
				'CN' => 'cid0cs',
				'Saudi Arabia' => 'dejavusans',
				'沙特阿拉伯' => 'dejavusans',
				'SA' => 'dejavusans',
		);
		$font = '';
		foreach ($country2font as $k => $c)
		{
			if ($content == $k)
			{
				$font = $c;
			}
		}
		if (!$font)
		{
			if (mb_strlen($content, 'utf-8') == strlen($content))
			{
				$font = 'helvetica';
			}
			else
			{
				foreach ($country2font as $k => $c)
				{
					if (strpos($content, $k) !== false)
					{
						$font = $c;
					}
				}
				if (!$font)
				{
					$font = 'dejavusansi';
				}
			}
		}
		return $font;
	}
	
	/**
	 * 根据时区获取对应时间
	 * @param 时间 , 时区($zone='+0800'), 格式    
	 * @return  string	格式后时间
	 */
	static function getTimeByZone($datetime, $zone, $format='Y-m-d H:i:s')
	{
		$dt = new DateTime();
		$tz = new DateTimeZone($zone);
		$dt->setTimestamp(strtotime($datetime));
		$dt->setTimezone($tz);
		return $dt->format($format);
	}
}